<?php

namespace app\common\model;

use think\Db;
use think\Model;

class OrderAppraise extends Model
{
    // 表名
    protected $name = 'order_appraise';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];

    /**
     * 订单评价
     * @param array $params
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function orderComment($params = [])
    {
        if (empty($params['user_id']) || empty($params['order_id'])) {
            $this->error = __('User ID Or Order ID Empty');
            return false;
        }

        $order = Order::where(['id' => $params['order_id'], 'user_id' => $params['user_id'], 'status' => 2])->find();
        if (!$order) {
            $this->error = __('Order does not exist');
            return false;
        }

        if ($order['is_appraise']) {
            $this->error = __('The order has been evaluated');
            return false;
        }

        $data = [
            'user_id'       => $params['user_id'],
            'recycler_id'   => $order['recycler_id'],
            'order_id'      => $params['order_id'],
            'receiving'     => $params['receiving'],
            'come'          => $params['come'],
            'service'       => $params['service'],
            'evaluate'      => trim($params['evaluate']),
        ];

        Db::startTrans();
        if (!$this->save($data)) {
            $this->error = __('Evaluation failed');
            Db::rollback();
            return false;
        }

        if (!Order::where(['id' => $params['order_id']])->update(['is_appraise' => 1, 'updatetime' => time()])) {
            $this->error = __('Order evaluation failed');
            Db::rollback();
            return false;
        }

        Db::commit();
        return true;
    }

}